package com.example.composetest

import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest


sealed interface ProfileEvent {
    data object Load : ProfileEvent
}

sealed interface ProfileState {
    data object Loading : ProfileState
    data class LoadFinished(val list: List<String>) : ProfileState
    data object Hidden : ProfileState
}

class ProfileViewModel(
    private val profilePresenter: ProfilePresenter = ProfilePresenter(MyUseCase())
) : MVIViewModel<ProfileState, ProfileEvent, Nothing>() {
    @Composable
    override fun state(events: Flow<ProfileEvent>): ProfileState {
        LaunchedEffect(Unit) {
            events.collectLatest { event ->

            }
        }
        return profilePresenter.presenter()
    }
}


class ProfilePresenter(
    private val useCase: MyUseCase
) {

    @Composable
    fun presenter(): ProfileState {
        var isLoading by remember { mutableStateOf(true) }
        var list: List<String>? by remember {
            mutableStateOf(emptyList())
        }
        LaunchedEffect(Unit) {
            isLoading = true
            list = runCatching {
                useCase.loadData()
            }.getOrNull()
            isLoading = false
        }

        return if (isLoading) {
            ProfileState.Loading
        } else list?.let {
            ProfileState.LoadFinished(list = it)
        } ?: ProfileState.Hidden
    }

}